<?php

namespace Database;

use PDO;
use PDOException;

class Connection {
    private static $instance = null;
    private $connection;
    private $config;
    
    /**
     * 私有构造函数，防止外部直接实例化
     */
    private function __construct(array $config) {
        $this->config = $config;
        $this->connect();
    }
    
    /**
     * 获取数据库连接实例（单例模式）
     */
    public static function getInstance(array $config = null) {
        if (self::$instance === null) {
            if ($config === null) {
                throw new \Exception("数据库配置不能为空");
            }
            self::$instance = new self($config);
        }
        return self::$instance;
    }
    
    /**
     * 建立数据库连接
     */
    private function connect() {
        $driver = $this->config['driver'];
        $host = $this->config['host'];
        $database = $this->config['database'];
        $username = $this->config['username'];
        $password = $this->config['password'];
        $charset = $this->config['charset'];
        
        try {
            $dsn = "{$driver}:host={$host};dbname={$database};charset={$charset}";
            $this->connection = new PDO($dsn, $username, $password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            ]);
        } catch (PDOException $e) {
            throw new \Exception("数据库连接失败: " . $e->getMessage());
        }
    }
    
    /**
     * 获取PDO连接实例
     */
    public function getPdo() {
        return $this->connection;
    }
    
    /**
     * 执行SQL查询
     */
    public function query($sql, $params = []) {
        try {
            $statement = $this->connection->prepare($sql);
            $statement->execute($params);
            return $statement;
        } catch (PDOException $e) {
            throw new \Exception("查询执行失败: " . $e->getMessage());
        }
    }
    
    /**
     * 开始事务
     */
    public function beginTransaction() {
        return $this->connection->beginTransaction();
    }
    
    /**
     * 提交事务
     */
    public function commit() {
        return $this->connection->commit();
    }
    
    /**
     * 回滚事务
     */
    public function rollBack() {
        return $this->connection->rollBack();
    }
    
    /**
     * 获取最后插入的ID
     */
    public function lastInsertId() {
        return $this->connection->lastInsertId();
    }
    
    /**
     * 防止克隆
     */
    private function __clone() {}
    
    /**
     * 防止反序列化
     */
    private function __wakeup() {}
}